package com.yanwq.sayhi.widget.anim;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.animation.LinearInterpolator;

/**
 * 作者：yanweiqiang。
 * 日期：2016/7/26 0026。
 */
public class AnimCompact {
    private int mLastPosition = -1;
    private boolean isFirstOnly = true;

    private CustomAnimators mCustomAnimators;

    public AnimCompact(CustomAnimators animators) {
        mCustomAnimators = animators;
    }

    public void onBindViewHolder(View itemView, int position) {
        if (!isFirstOnly || position > mLastPosition) {
            for (Animator anim : getAnimators(itemView)) {
                anim.start();
            }
            mLastPosition = position;
        } else {
            clear(itemView);
        }
    }

    public void setStartPosition(int start) {
        mLastPosition = start;
    }

    public void setFirstOnly(boolean firstOnly) {
        isFirstOnly = firstOnly;
    }

    protected Animator[] getAnimators(View view) {
        if (mCustomAnimators == null) {
            ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f);
            alpha.setDuration(500);
            alpha.setInterpolator(new LinearInterpolator());
            return new ObjectAnimator[]{alpha};
        } else {
            return mCustomAnimators.animators(view);
        }
    }

    public static void clear(View v) {
        ViewCompat.setAlpha(v, 1);
        ViewCompat.setScaleY(v, 1);
        ViewCompat.setScaleX(v, 1);
        ViewCompat.setTranslationY(v, 0);
        ViewCompat.setTranslationX(v, 0);
        ViewCompat.setRotation(v, 0);
        ViewCompat.setRotationY(v, 0);
        ViewCompat.setRotationX(v, 0);
        // @TODO https://code.google.com/p/android/issues/detail?id=80863
        //        ViewCompat.setPivotY(v, v.getMeasuredHeight() / 2);
        v.setPivotY(v.getMeasuredHeight() / 2);
        ViewCompat.setPivotX(v, v.getMeasuredWidth() / 2);
        ViewCompat.animate(v).setInterpolator(null);
    }

    public interface CustomAnimators {

        Animator[] animators(View view);
    }
}
